package org.jjche.serialize.transformer;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import net.dreamlu.mica.core.spring.SpringContextUtil;
import org.jjche.common.annotation.transform.TransformFK;
import org.jjche.common.transformer.IForeignKeyTransformer;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * 外键转换器
 * 可在本地数据将id转换成另一个指定属性
 *
 * @author R
 * @see TransformFK （Mapper转换注解）
 */
@Component
public class ForeignKeyTransformer implements IForeignKeyTransformer<Serializable> {

    @Override
    public String transform(@NonNull Serializable id, @NonNull Class<? extends BaseMapper<?>> clazz, @NonNull String to) {
        BaseMapper<?> mapper = SpringUtil.getBean(clazz);
        Object entity = mapper.selectById(id);
        if (entity == null) {
            StaticLog.warn("转换警告：{}类根据id={}，找不到任何数据！", clazz.getSimpleName(), id);
            return null;
        }
        Field field = ReflectionUtils.findField(entity.getClass(), to);
        Assert.notNull(field, "找不到该属性，请检查注解@TransformFK的field字段配置：" + to);
        ReflectionUtils.makeAccessible(field);
        return (String) ReflectionUtils.getField(field, entity);
    }
}
